var OrdersModule = function () {
    var editable = function () {

        return {
            init: function () {
            	//获取文件名
            	function getFilename(s){
            		if(undefined == s||'' == s){
            			return '';
            		}
            		var names = s.split("/");
            		if(names.length <= 1&&s.indexOf("\\") >= 1 ){ 
            			names = s.split("\\");
            		}
                	var filename = names[names.length-1];
                	return filename;
            	}
            	//格式化金额
            	function fmoney(s, n) {  
            	   if(s == "" || undefined == s){
            		   return "---";
            	   }
                   n = n > 0 && n <= 20 ? n : 2;  
                   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";//更改这里n数也可确定要保留的小数位  
                   var l = s.split(".")[0].split("").reverse(),  
                   r = s.split(".")[1];  
                   t = "";  
                   for(i = 0; i < l.length; i++ )  
                   {  
                      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
                   }
                   var str = t.split("").reverse().join("") + "." + r.substring(0,2);
                   return str;//保留2位小数  如果要改动 把substring 最后一位数改动就可  
                }
            	function toPercent(num) {
            		//.toFixed(2)小数位为2位
            		return Number(num * 100).toFixed(2) + '%';
            	}
                //防止多次初始化
                var oTableB = null;
                var oTableCharge = null;
                var oTableConmission = null;
                
                // 详情页加载
            	var id = $("#order_id").attr("value");
            	var investorId = $("#investor_id").attr("value");
            	var employeeId = $("#employee_id").attr("value");
            	var employeeName = $("#employee_name").attr("value"); 
            	var json = "";
                var form = $("form#queryadaForm").serializeJSON();
            	var js = form.replace('}', '');
            	json = js + json +'"id":"'+id+ '"}';
                $.ajax({
                	"contentType":"application/json; charset=UTF-8",
                	type:"post",
                    url: ctx + "/orders/orderDetail",
                    data: json,
                    dataType:"json",
                    success: function(msg){
                    	msg.orderAmount = fmoney(msg.orderAmount);
                    	if(msg.gradeId == undefined || msg.gradeId == ""){
                            msg.gradeId = null;
                            // msg.grade = null;
                            // msg.subScopeStart = null;
                            // msg.subScopeEnd = null;
                            // msg.remark = null;
                            // msg.prospectiveEarnings = null;
                        }
                        if(msg.prospectiveEarnings == undefined){
                            msg.prospectiveEarnings = null;
                        }
                        if(msg.bankCard == undefined || msg.bankCard == ""){
                            msg.bankCard = null;
                        }else{
                            msg.bankCard = imagePrefix + msg.bankCard;
                        }
                    	if(msg.agentId == undefined){
                            msg.agentId = null;
                        }
                    	if(undefined != msg.paidAmout){
                    		msg.paidAmout = fmoney(msg.paidAmout);
                    	}else{
                    		msg.paidAmout = "---";
                    	}
                    	if(undefined != msg.subFeeTotal){
                    		msg.subFeeTotal = fmoney(msg.subFeeTotal);
                    	}else{
                    		msg.subFeeTotal = "---";
                    	}
                    	if(undefined != msg.handlingFee){
                    		msg.handlingFee = fmoney(msg.handlingFee);
                    	}else{
                    		msg.handlingFee = "---";
                    	}
                    	if(undefined != msg.orderAllAmount){
                    		msg.orderAllAmount = fmoney(msg.orderAllAmount);
                    	}else{
                    		msg.orderAllAmount = "---";
                    	}
                    	$("#detialBody").empty();// clean
                    	msg.contactFilename = getFilename(msg.contactFile);
                    	msg.videoManagerName = getFilename(msg.videoManager);
                    	msg.videoUserName = getFilename(msg.videoUser);
                    	if(msg.idcardFront != undefined || msg.idcardFront != null){
                    		msg.idcardFront = imagePrefix + msg.idcardFront;
                    	}
                    	if(msg.idcardBack != undefined || msg.idcardBack != null){
                        	msg.idcardBack = imagePrefix + msg.idcardBack;
                    	}
                    	if(msg.paySignManager != undefined || msg.paySignUser != undefined){
                    		msg.signState = 1;
                    	}else{
                    		msg.signState = 0;
                    	}
                    	if(msg.paySignManager != undefined || msg.paySignManager != null){
                    		msg.paySignManager = imagePrefix + msg.paySignManager;
                    	}
                    	if(msg.paySignUser != undefined || msg.paySignUser != null){
                        	msg.paySignUser = imagePrefix + msg.paySignUser;
                    	}
                    	if(msg.voucherList != undefined || msg.voucherList.length != 0){
                    		for(var i = 0;i < msg.voucherList.length; i++){
                    			msg.voucherList[i].filePath = imagePrefix + msg.voucherList[i].filePath;
                    		}
                    	}
                    	var tmpl = $("#detialTemplate").tmpl(msg).appendTo("#detialBody");
                    	var modal = $('#myModal2').modal('show');
                    	if (oTableB != null) { 
                    		//为了避免多次初始化datatable()
                    		oTableB = null;
                            //fvTable.fnAdjustColumnSizing(); //重新判断列宽度，实际执行并没有效果　
                        }
                    	if (oTableCharge != null) { 
                    		//为了避免多次初始化datatable()
                    		oTableCharge = null;
                            //fvTable.fnAdjustColumnSizing(); //重新判断列宽度，实际执行并没有效果　
                        }
                    	if (oTableConmission != null) { 
                    		//为了避免多次初始化datatable()
                    		oTableConmission = null;
                            //fvTable.fnAdjustColumnSizing(); //重新判断列宽度，实际执行并没有效果　
                        }
                    	if(msg.payContacts > 0 ){
	                    	oTableB = $('#ordersVisitEditable1').dataTable({
	                    		"lengthChange" : false,
	                    		"autoWidth":true,
	                            "displayLength": 0,
	                            "paginate": false, //翻页功能
	                            "paginate":false,//是否使用分页 
	                            "sort": false, //排序功能
	                            "jQueryUI": false, 
	                            "info": false,//页脚信息
	                            "language": {
	                                "zeroRecords":"数据为空",
	                            },
	                            "columnDefs": [
	        						 { "width": "30%", "targets": 0 },
	        						 { "width": "40%", "targets": 1 },
	        						 { "width": "30%", "targets": 2 }
	                            ],
	                            "columns": [
	                               { "data": "employeeName","defaultContent": "<center>---<center>"},
	                               { "data": "content","defaultContent": "<center>---<center>" },
	                               { "data": "visitTime","defaultContent": "<center>---<center>" }
	                           ],
	                           "scrollX": "120%",
	                           "scrollXInner": "100%",
	                           "destory":true,
	                           "filter" : false,
	                           "processing": false,
	                           "serverSide": true,
	                           "ajaxSource": ctx + "/orders/contacts",
	                           "serverMethod": "post",
	                           "fnRowCallback" : function(nRow, aData, displayIndex) {
	                        	   var employee = "<center>" + aData.employeeName + " 工号:" + aData.employeeNo + "</center>";
	                        	   $('td:eq(0)', nRow).html(employee);
	                        	   var content = "<center>" + aData.content + "</center>";
	                        	   $('td:eq(1)', nRow).html(content);
	                        	   if(aData.visitTime == undefined){
	                        		   var visitTime = "<center>-</center>";
	                            	   $('td:eq(2)', nRow).html(visitTime);
	                        	   }else{
	                        		   var visitTime = "<center>" + aData.visitTime + "</center>";
	                            	   $('td:eq(2)', nRow).html(visitTime);
	                        	   }
	                               return nRow;
	                           },
	                           "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                        	   var json = "";
	                        	   var s;
	        	                   for (var i = 0; i < dataSet.length; i++) {
	        	                       s = dataSet[i];
	        	                   	   if (s.name == 'sEcho') {
	        	                   		   json = json + '"echo":' + s.value;
	        		                   } else if (s.name == 'iDisplayStart') {
	        		                	   json = json + ',"page":' + s.value;
	        		                   } else if (s.name == 'iDisplayLength') {
	        		                	   json = json + ',"pageSize":' + s.value;
	        		                   }
	        	                   }
	        	                   var form = $("form#queryadaForm").serializeJSON();
	                           	   var js = form.replace('}', '');
	                           	   json = js + json +',"id":"'+id+ '"}';
	                               $.ajax({
	                               	"contentType":"application/json; charset=UTF-8",
	                                   "dataType" : 'json',
	                                   "type" : "POST",
	                                   "url" : ajaxSource,
	                                   "data" : json,
	                                   "success" : fnCallback
	                               });
	                           },
	                        });
                    	}
                    	if(msg.payCount >0 ){
	                    	oTableCharge = $('#ordersCharge').dataTable({
	                    		"lengthChange" : false,
	                            "displayLength": 0,
	                            "autoWidth":true,
	                            "paginate": false, //翻页功能
	                            "filter":false, //过滤功能
	                            "paginate":false,//是否使用分页 
	                            "sort": false, //排序功能
	                            "jQueryUI": false, 
	                            "info": false,//页脚信息
	                            "language": {
	                                "zeroRecords":"数据为空",
	                            },
	                            "columnDefs": [
	                  				{ "width": "30%", "targets": 0 },
	                				{ "width": "40%", "targets": 1 },
	                				{ "width": "30%", "targets": 2 } 
	                            ],
	                            "columns": [
	                               { "data": "paySerial","defaultContent": "<center>---<center>" },
	                               { "data": "payAmount","defaultContent": "<center>---<center>" },
	                               { "data": "payTime", "defaultContent": "<center>---<center>"},
	                           ],
	                           "scrollX": "120%",
	                           "scrollXInner": "100%",
	                           "filter" : false,
	                           "processing": false,
	                           "serverSide": true,
	                           "ajaxSource": ctx + "/orders/pay",
	                           "serverMethod": "post",
	                           "fnRowCallback" : function(nRow, aData, displayIndex) {
	                        	   var paySerial = "";
	                        	   if(aData.paySerial == undefined){
	                        		   paySerial = "<center>---<center>";
	                        	   }else{
	                        		   paySerial = "<center>" + aData.paySerial + "</center>";
	                        	   }
	                        	   $('td:eq(0)', nRow).html(paySerial);
	                        	   var payAmount = "<center>" + fmoney(aData.payAmount) + "</center>";
	                        	   $('td:eq(1)', nRow).html(payAmount);
	                        	   var payTime = "<center>" + aData.payTime + "</center>";
	                        	   $('td:eq(2)', nRow).html(payTime);
	                               return nRow;
	                           },
	                           "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                        	   var json = "";
	                        	   var s;
	        	                   for (var i = 0; i < dataSet.length; i++) {
	        	                       s = dataSet[i];
	        	                   	   if (s.name == 'sEcho') {
	        	                   		   json = json + '"echo":' + s.value;
	        		                   } else if (s.name == 'iDisplayStart') {
	        		                	   json = json + ',"page":' + s.value;
	        		                   } else if (s.name == 'iDisplayLength') {
	        		                	   json = json + ',"pageSize":' + s.value;
	        		                   }
	        	                   }
	        	                   var form = $("form#queryadaForm").serializeJSON();
	                           	   var js = form.replace('}', '');
	                           	   json = js + json +',"id":"'+id+ '"}';
	                               $.ajax({
	                               	"contentType":"application/json; charset=UTF-8",
	                                   "dataType" : 'json',
	                                   "type" : "POST",
	                                   "url" : ajaxSource,
	                                   "data" : json,
	                                   "success" : fnCallback
	                               });
	                           },
	                        });
                    	}
                    	if(msg.payCommission > 0){
	                    	oTableConmission = $('#orderCommission').dataTable({
	                    		"lengthChange" : false,
	                            "displayLength": 0,
	                            "autoWidth":true,
	                            "paginate": false, //翻页功能
	                            "filter":false, //过滤功能
	                            "paginate":false,//是否使用分页 
	                            "sort": false, //排序功能
	                            "jQueryUI": false, 
	                            "info": false,//页脚信息
	                            "language": {
	                                "zeroRecords":"数据为空",
	                            },
	                            "columnDefs": [
	                  				
	                            ],
	                            "columns": [
	                               { "data": "employeeName",'sortable': false,"defaultContent": "<center>---<center>","targets": [0],"width": "25%"},
	                               { "data": null,'sortable': false,"defaultContent": "<center>---<center>","targets": [0],"width": "25%"},
	                               { "data": null,'sortable': false,"defaultContent": "<center>---<center>","targets": [0],"width": "25%"},
	                               { "data": null,'sortable': false,"defaultContent": "<center>---<center>","targets": [0],"width": "25%"},
	                           ],
	                           "scrollX": "120%",
	                           "scrollXInner": "100%",
	                           "filter" : false,
	                           "processing": false,
	                           "serverSide": true,
	                           "ajaxSource": ctx + "/commissionPay/query",
	                           "serverMethod": "post",
	                           "fnRowCallback" : function(nRow, aData, displayIndex) {
	                        	   var employeeName = "<center>" + aData.employeeName + "</center>";
	                        	   $('td:eq(0)', nRow).html(employeeName);
	                        	   /*var commissionRate = "<center>" + aData.commissionRate + "</center>";
	                        	   $('td:eq(1)', nRow).html(commissionRate);
	                        	   var commission = "<center>" + fmoney(aData.commission) + "</center>";
	                        	   $('td:eq(2)', nRow).html(commission);
	                        	   var state = "<center>" + aData.state + "</center>";
	                        	   $('td:eq(3)', nRow).html(state);*/
	                        	   if(aData.dividendRate == undefined||aData.dividendRate==0||aData.dividendRate==null){
	                        		   $('td:eq(1)', nRow).html("<center>" + "佣金："+
	                        				   toPercent(aData.commissionRate) + "</center>");
	                        		   $('td:eq(2)', nRow).html("<center>" + "佣金："+
	                        				   fmoney(aData.orderAmount*aData.commissionRate)+"&nbsp;元" + "</center>");
	                        	   }else if(aData.commissionRate == undefined||aData.commissionRate==0||aData.commissionRate==null){
	                        		   $('td:eq(1)', nRow).html("<center>" + "提成："+
	                        				   toPercent(aData.dividendRate) + "</center>");
	                        		   $('td:eq(2)', nRow).html("<center>" + "提成："+
	                        				   fmoney(aData.orderAmount*aData.dividendRate)+"&nbsp;元" + "</center>");
	                        	   }else{
	                        		   $('td:eq(1)', nRow).html("<center>" + "提成："+
	                        				   toPercent(aData.dividendRate)+"&nbsp;"+"佣金："+
	                        				   toPercent(aData.commissionRate) + "</center>");
	                        		   $('td:eq(2)', nRow).html("<center>" + "提成："+
	                        				   fmoney(aData.orderAmount*aData.dividendRate)+"&nbsp;元"+
	                        				   "&nbsp;"+"佣金："+fmoney(aData.orderAmount*aData.commissionRate)+"&nbsp;元" + "</center>");
	                        	   }
	                        	   var auditState;
	                        	   if(aData.state == 0){
	                        		   auditState = "未审核";
	                        	   }else if(aData.state == 1){
	                        		   auditState = "已审核";
	                        	   }else if(aData.state == 2){
	                        		   auditState = "已到账";
	                        	   }else{
	                        		   auditState = "未审核";
	                        	   }
	                        	   
	                        	   $('td:eq(3)', nRow).html("<center>" + auditState + "</center>");
	                               return nRow;
	                           },
	                           "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                        	   var json = "";
	                        	   var s;
	        	                   for (var i = 0; i < dataSet.length; i++) {
	        	                       s = dataSet[i];
	        	                   	   if (s.name == 'sEcho') {
	        	                   		   json = json + '"echo":' + s.value;
	        		                   } else if (s.name == 'iDisplayStart') {
	        		                	   json = json + ',"page":' + s.value;
	        		                   } else if (s.name == 'iDisplayLength') {
	        		                	   json = json + ',"pageSize":' + s.value;
	        		                   }
	        	                   }
	        	                   var form = $("form#queryadaForm").serializeJSON();
	                           	   var js = form.replace('}', '');
	                           	   json = js + json +',"orderId":"'+id+ '"}';
	                               $.ajax({
	                               	"contentType":"application/json; charset=UTF-8",
	                                   "dataType" : 'json',
	                                   "type" : "POST",
	                                   "url" : ajaxSource,
	                                   "data" : json,
	                                   "success" : fnCallback
	                               });
	                           },
	                        });
                    	}
                    	},
                    error: function (msg) {
                    	bootbox.alert(msg.message);
                    }
                });
                
                //查看线下支付申请审核记录
                $('#checkOfflineApplyRecord').click(function(){
            		/*var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;*/
                	$.ajax({
                     	 type:"post",
                         url: ctx + "/orders/checkOfflineApply",
                         data:"id=" + id,
                         dataType:"json",
                         success: function(msg){
                         	$("#auditBody").empty();
                         	var tmpl = $("#auditTemplate").tmpl(msg.data).appendTo("#auditBody");
                         	var modal = $('#offlineAuditMomal').modal('show');
                         	modal.on("hidden.bs.modal",function(e){
                         		$(this).removeData();
                         		$("#auditBody").empty();
                         	});
//                         	$('#auditBtn').click(function(){
//                         		var json = $("form#auditForm").serializeJSON();
//                         		$.ajax({
//                         			"contentType":"application/json; charset=UTF-8",
//                                 	type:"post",
//                                     url: ctx + "/orders/offlineApplyAudit",
//                                     data: json,
//                                     dataType:"json",
//                                     success: function(msg){
//                                     	if(msg.code == 1){
//                                     		bootbox.alert("操作成功");
//                                     		$('#offlineAuditMomal').modal('hide');
//                                     		oTable.fnClearTable();
//                                     	}else{
//                                     		bootbox.alert(msg.message);
//                                     		$('#offlineAuditMomal').modal('hide');
//                                     	}
//                                     },
//                                     error: function (msg) {
//                                     	bootbox.alert(msg.message);
//                                     	$('#offlineAuditMomal').modal('hide');
//                                     }
//                                 });
//                             });
                         },
                         error: function (msg) {
                         	bootbox.alert(msg.message);
                         }
                     });
            	});
                
                //添加联系记录
                $('#addVisit').click(function(){
            		/*var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;*/
                	var modal = $('#addVisitModal').modal('show');
                	modal.on("hidden.bs.modal",function(e){
                		$(this).removeData();
                	});
                	$("#addVisitConfirm").unbind("click").click(function(){
                		var form = $('#addVisitForm').serializeJSON();
                		var js = form.replace('}',',');
                		var json  = js + '"orderId":"' + id + '","investorId":"' + investorId + 
                		'","employeeId":"' + employeeId + '","employeeName":"' + employeeName + '"}';
                		$.ajax({
                			contentType:"application/json; charset=UTF-8",
                            url: ctx + '/orders/addVisit',
                            type: 'post',
                            secureuri: false, //一般设置为false
                            dataType: 'json',
                            data: json,// json对象
                            success: function(msg){
                            	if(0 == msg.code){
                            		bootbox.alert(msg.message);
                            		return;
                            	}
                            	$('#contentText').val('');
                            	bootbox.alert("联系记录新增成功！");
                            	//重新绘制表格
                            	oTableB.fnDraw(false);
                            },
                            error: function(msg){
                            	bootbox.alert(msg.message);
                            }
                        });
                        modal.modal('hide');
                    });
            	});
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();